package com.zyf.project.binaryproto.converter.impl.dynamic;

import com.zyf.project.binaryproto.converter.impl.AbstractDynamicValueConverter;
import org.jetbrains.annotations.NotNull;
import utils.binary.impl.BytesSlice;
import utils.binary.BytesUtils;
import utils.binary.io.BytesOutputBuffer;

/**
 * @author Zhou Yifan
 */
public class BytesValueConverter extends AbstractDynamicValueConverter {

    public BytesValueConverter() {
        super(byte[].class);
    }

    /**
     * 写入一个动态长度的值，以一个头部的长度字节开始
     *
     * @param value  待写入的值
     * @param buffer 目标缓存
     * @return 写入的字节数
     */
    @Override
    public int encode(Object value, BytesOutputBuffer buffer) {
        byte[] bytes = value == null ? BytesUtils.EMPTY_BYTES : (byte[]) value;
        int size = bytes.length;
        size += writeSize(size, buffer);
        buffer.write(bytes);
        return size;
    }

    /**
     * 数据片解码
     *
     * @param dataSlice 数据片
     * @return 解码后的对象
     */
    @Override
    public Object decode(@NotNull BytesSlice dataSlice) {
        return dataSlice.getBytesCopy();
    }
}
